package com.qjc.sqlInjector;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: MyDeleteById
 * @Description: 填充属性值的删除
 * @Author: qjc
 * @Date: 2021/9/6 4:53 下午
 */
public class MyDeleteByIdWithFill extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql;
        SqlMethod sqlMethod;
        if (tableInfo.isLogicDelete()) {
            // 进行逻辑删除
            List<TableFieldInfo> fieldInfos = getWithUpdateFillFields(tableInfo);
            // 删除时自动填充需要填充的属性值
            String sqlLogicSet = "SET " + fieldInfos.stream().map(i -> i.getSqlSet(null)).collect(Collectors.joining(EMPTY))
                    + tableInfo.getLogicDeleteSql(false, false);
            sql = String.format(
                    "<script>\nUPDATE %s %s WHERE %s=#{%s}\n</script>",
                    tableInfo.getTableName(),
                    sqlLogicSet,
                    tableInfo.getKeyColumn(),
                    tableInfo.getKeyProperty());
            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
            return addUpdateMappedStatement(mapperClass, modelClass, "myDeleteByIdWithFill", sqlSource);
        } else {
            sqlMethod = SqlMethod.DELETE_BY_ID;
            sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(),
                    tableInfo.getKeyProperty());
            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
            return this.addDeleteMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource);
        }
    }

    /**
     * 过滤出更新时进行填充信息的字段列表
     *
     * @param
     * @return
     * @author qjc
     * @date 2021/9/6 5:09 下午
     */
    private List<TableFieldInfo> getWithUpdateFillFields(TableInfo tableInfo) {
        return tableInfo.getFieldList().stream()
                .filter(TableFieldInfo::isWithUpdateFill)
                .collect(Collectors.toList())
                ;
    }
}
